<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Sepcore
 * @copyright  Copyright 2010-2012 SocialEnginePro
 * @license    http://www.socialenginepro.com
 * @author     altrego aka Vadim ( provadim@gmail.com )
 */

class Sepcore_AdminIndexController extends Core_Controller_Action_Admin {

  public function settingsAction() {

	$this->view->navigation = Engine_Api::_()->getApi('menus', 'core')
		->getNavigation('sepcore_admin_main', array(), 'sepcore_admin_main_settings');

	$this->view->form = $form = new Sepcore_Form_Admin_Global();

	if (!$this->getRequest()->isPost())
		return;

	if (!$form->isValid($this->getRequest()->getPost()))
		return;

	$form->save();

  }


  public function pluginsAction() {

	$this->view->navigation = Engine_Api::_()->getApi('menus', 'core')
		->getNavigation('sepcore_admin_main', array(), 'sepcore_admin_main_plugins');

	$plugins = $this->_getPluginsInfo();
	if ( $plugins['result']===0 ) {
		$this->view->error = $plugins['message'];
		return;
	}
	$this->view->plugins = $plugins = $this->_checkInstalledPlugins($plugins);

  }


  public function installedAction() {

	$this->view->navigation = Engine_Api::_()->getApi('menus', 'core')
		->getNavigation('sepcore_admin_main', array(), 'sepcore_admin_main_installed');

	$plugins = $this->_getPluginsInfo();
	if ( $plugins['result']===0 ) {
		$this->view->error = $plugins['message'];
		return;
	}
	$this->view->plugins = $plugins = $this->_checkInstalledPlugins($plugins);

  }


  public function installAction() {

	$this->view->navigation = Engine_Api::_()->getApi('menus', 'core')
		->getNavigation('sepcore_admin_main', array());

	$package = $this->_getParam('package', NULL);

	$plugins = $this->_getPluginsInfo();

	if ( $plugins['result']===0 ) {
		$this->view->error = $plugins['message'];
		return;
	}
	$this->view->plugins = $plugins = $this->_checkInstalledPlugins($plugins);

	if ( !$plugins[$package]['license'] ) {
		$this->view->error = 'You have no licence for this plugin!';
		return;
	}

		// if we downloaded package sucessfully
	if ( $this->_getPackage($plugins[$package]['name'], $plugins[$package]['link_package']) ){

		$viewer = Engine_Api::_()->user()->getViewer();
		$authKeyRow = Engine_Api::_()->getDbtable('auth', 'core')->getKey($viewer, 'package');
		$this->view->authKey = $authKey = $authKeyRow->id;
		$installUrl = rtrim($this->view->baseUrl(), '/') . '/install';
		if( strpos($this->view->url(), 'index.php') !== false ) {
			$installUrl .= '/index.php';
		}
		$return = 'http://'.$_SERVER['HTTP_HOST'].$installUrl.'/manage/select';
		$installUrl .= '/auth/key' . '?key=' . $authKey . '&uid=' . $viewer->getIdentity() .'&return=' .$return;
		$this->view->installUrl = $installUrl;
		return $this->_helper->redirector->gotoUrl($installUrl, array('prependBase' => false));

	} else {

		$this->view->error = 'Can`t download package from SocialEnginePro server. Try again later.';

	}

  }


  public function contactAction() {

	$this->view->navigation = Engine_Api::_()->getApi('menus', 'core')
		->getNavigation('sepcore_admin_main', array(), 'sepcore_admin_main_contact');

	$this->view->form = $form = new Sepcore_Form_Admin_Contact();

	$settings = Engine_Api::_()->getApi('settings', 'core');

	$admin_email = $settings->getSetting('sepcore.client.email', '');

	if ( empty($admin_email) ) {
		$this->view->error = 'To send messages you must specify your SocialEnginePro account on Global Settings page';
		return;
	}

	if ( !$this->getRequest()->isPost() )
		return;

	$post = $this->getRequest()->getPost();

	if ( !$form->isValid($post) )
		return;

	$message = '
		<p><strong>client email:</strong> <a href="mailto:' . $admin_email . '">' . $admin_email . '</p>
		<p><strong>domain:</strong> <a href="http://' . $_SERVER['HTTP_HOST'] . '">' . $_SERVER['HTTP_HOST'] . '</p>
		<p>' . $post['message'] . '</p>
	';

	$mail = new Zend_Mail('UTF-8');
	$mail->setBodyHtml($message);
	$mail->setFrom($admin_email);
	$mail->addTo('support@socialenginepro.com');
	$mail->setSubject($post['subject']);
	$mail->send();
	$this->view->message = 'Your message has been sent';
  }


  public function _getPackage($plugin_name, $plugin_url) {
	$tmp_archives_path = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'temporary' . DIRECTORY_SEPARATOR . 'package' . DIRECTORY_SEPARATOR . 'archives/';
	$curl = curl_init($plugin_url);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	$result = curl_exec($curl);
	curl_close($curl);
	$result = file_put_contents($tmp_archives_path . $plugin_name . '.tar', $result);
	return $result;
  }


  public function _getPluginsInfo($url) {
	$settings = Engine_Api::_()->getApi('settings', 'core');
	$data_string = 'domain=' . urlencode($_SERVER['HTTP_HOST']) . '&account=' . $this->_getAccount();

	$query = 'http://socialenginepro.com/license/p.php?' . $data_string;
	$curl = curl_init($query);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	$result = curl_exec($curl);
	$result = json_decode($result, true);
	curl_close($curl);

	if ( empty($result) ) {
		return array('result'=>0, 'message'=>'can`t get plugin info');
	}
	return $result;
  }


  public function _checkInstalledPlugins($plugins) {
	$plugin_keys = '"'.str_replace(',', '","', implode(',', array_keys($plugins)) ).'"';

	$table = Engine_Api::_()->getDbtable('modules', 'core');
	$select = $table->select()->where('`name` IN ('.$plugin_keys.')');
	$notsorted_installed = $table->fetchAll($select)->toArray();
	foreach ( $notsorted_installed as $plugin ) {
		$plugins[$plugin['name']]['installed'] = 1;
		$plugins[$plugin['name']]['installed_version'] = $plugin['version'];
		$plugins[$plugin['name']]['upgrade'] = ( version_compare($plugin['version'], $plugins[$plugin['name']]['version'])===-1 ) ? 1 : 0;
	}

	return $plugins;
  }


  public function _getAccount() {
	$settings = Engine_Api::_()->getApi('settings', 'core');
	return md5(md5($settings->getSetting('sepcore.client.email', '')) . $settings->getSetting('sepcore.client.password', ''));
  }

}